library(mclogit)         #for conditional logit models 
library(stargazer)       #for model tables in latex
library(survival)        #alternative package for conditional logistic regressions
library(tidyverse)       #for data-wrangling

##data-wrangling----
BrSenSwitch <- read.csv("BrSenSwitch.csv", sep = ";") %>%
               mutate(fusao = ifelse(is.na(fusao), 0, fusao)) %>%
               mutate(fissao = ifelse(is.na(fissao), 0, fissao)) %>%
               mutate(partido_novo = ifelse(is.na(partido_novo), 0, partido_novo)) %>%
               mutate(home_inverted = 1-home) %>%
               filter(partido_novo != 1,
                      fissao != 1) %>%
               mutate(to_be_elected = case_when(legislatura == 48 ~ 1,
                                                legislatura == 49 ~ 2,
                                                legislatura == 50 ~ 1,
                                                legislatura == 51 ~ 2,
                                                legislatura == 52 ~ 1,
                                                legislatura == 53 ~ 2,
                                                legislatura == 54 ~ 1,
                                                legislatura == 55 ~ 2,
                                                legislatura == 56 ~ 1))

double_renovation <- BrSenSwitch %>% filter(to_be_elected == 2) 
single_renovation <- BrSenSwitch %>% filter(to_be_elected == 1)

##1st Robustness Check----
avv_a <- mclogit(
  y|choice ~ office + dif1 + party_str2 + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = BrSenSwitch)

avv_b <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str2 + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = BrSenSwitch)

avv_c <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str2*elec_comp + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = BrSenSwitch)

avv_d <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str2 + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = single_renovation)

avv_e <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str2 + party_str2*elec_comp +
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = single_renovation)

avv_f <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str2 + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = double_renovation)

avv_g <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str2*elec_comp + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = double_renovation)

#models with clogit
avv1 = clogit(y ~ office + dif1 + party_str2 + 
                home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                strata(choice), data=BrSenSwitch)

avv2 = clogit(y ~ alt_swps + dif1 + party_str2 + 
                home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                strata(choice), data=BrSenSwitch)

avv3 = clogit(y ~ alt_swps + dif1 + party_str2*elec_comp + 
                home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                strata(choice), data=BrSenSwitch)

avv4 = clogit(y ~ alt_swps + dif1 + party_str2 + 
                home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                strata(choice), data=single_renovation)


avv5 = clogit(y ~ alt_swps + dif1 + party_str2 + party_str2*elec_comp +
                home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                strata(choice), data=single_renovation)


avv6 = clogit(y ~ alt_swps + dif1 + party_str2 + 
                home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                strata(choice), data=double_renovation)

avv7 = clogit(y ~ alt_swps + dif1 + party_str2*elec_comp + 
                home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                strata(choice), data=double_renovation)

stargazer(avv1, avv2, avv3, avv4, avv5, avv6, avv7, type = "text")

stargazer(avv_a, avv_b, avv_c, avv_d, avv_e, avv_f, avv_g, 
          column.labels   = c("Full Dataset", "M = 1", "M = 2"),
          column.separate = c(3, 2, 2),
          no.space=T, order = c(1,2,3,4,7,5,6,8,9, 10), digits = 2, 
          covariate.labels = c("Preisdential Coalition", "Weighted Participation in Coalition", 
                               "Ideological Distance", "Party Strength (Governorship)", "Party Strength (Governorship) * Electoral Competition",
                               "Home Party", "Governor's Coalition", "Surrogate", "Number of Legislatures",
                               "Rural Population"),
          ##input from clogit models for more detailed infmation
          add.lines=list(c("N","246,994","209,727","209,727", "110,246", "110,246", "99,481", "99,481"),
                         c("R$^{2}", "0.334", "0.342", "0.342", "0.340", "0.340", "0.344", "0.344"),
                         c("Max. Possible R2", "0.339", "0.346", "0.345",  "0.345", "0.345", "0.347", "0.347"),
                         c("Log Likelihood", "-886.189", "-644.550",  "-644.459", "-397.750", "-397.705", "-237.023", "-236.889")))

##2nd Robustness Check----
so_br_senswitch <- BrSenSwitch %>%
                   select(senador, legislatura, ano, mes, partido_final) %>%
                   unique() %>%
                   group_by(partido_final, legislatura, ano, mes) %>%
                   summarise(n = n()) %>% 
                   ungroup()

cutting <- so_br_senswitch %>%
           filter(n >= 4) %>%
           mutate(pylym = paste0(partido_final, "_", legislatura, "_", ano, "_", mes)) %>%
           select(pylym) %>%
           pull()

so_first_dataset <- BrSenSwitch %>%
                    mutate(pylym = paste0(partido_final, "_", legislatura, "_", ano, "_", mes)) %>%
                    filter(pylym %in% cutting)

so_double_renovation <- so_first_dataset %>% filter(to_be_elected == 2) 
so_single_renovation <- so_first_dataset %>% filter(to_be_elected == 1)


so_1a <- mclogit(
  y|choice ~ office + dif1 + party_str + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = so_first_dataset)

so_1b <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = so_first_dataset)

so_1c <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str*elec_comp + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = so_first_dataset)

so_1d <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = so_single_renovation)

so_1e <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str + party_str*elec_comp +
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = so_single_renovation)

so_1f <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = so_double_renovation)

so_1g <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str*elec_comp + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = so_double_renovation)


cl_1a = clogit(y ~ office + dif1 + party_str + 
                 home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                 strata(choice), data=so_first_dataset)

cl_1b = clogit(y ~ alt_swps + dif1 + party_str + 
                 home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                 strata(choice), data=so_first_dataset)

cl_1c = clogit(y ~ alt_swps + dif1 + party_str*elec_comp + 
                 home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                 strata(choice), data=so_first_dataset)

cl_1d = clogit(y ~ alt_swps + dif1 + party_str + 
                 home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                 strata(choice), data=so_single_renovation)


cl_1e = clogit(y ~ alt_swps + dif1 + party_str + party_str*elec_comp +
                 home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                 strata(choice), data=so_single_renovation)


cl_1f = clogit(y ~ alt_swps + dif1 + party_str + 
                 home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                 strata(choice), data=so_double_renovation)

cl_1g = clogit(y ~ alt_swps + dif1 + party_str*elec_comp + 
                 home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                 strata(choice), data=so_double_renovation)

stargazer(cl_1a, cl_1b, cl_1c, cl_1d, cl_1e, cl_1f, cl_1g, type = "text")


stargazer(so_1a, so_1b, so_1c, so_1d, so_1e, so_1f, so_1g, 
          column.labels   = c("Full Dataset", "M = 1", "M = 2"),
          column.separate = c(3, 2, 2),
          no.space=T, order = c(1,2,3,4,7,5,6,8,9, 10), digits = 2, 
          covariate.labels = c("Preisdential Coalition", "Weighted Participation in Coalition", 
                               "Ideological Distance", "Party Strength", "Party Strength * Electoral Competition",
                               "Home Party", "Governor's Coalition", "Surrogate", "Number of Legislatures",
                               "Rural Population"),
          ##input from clogit models for more detailed infmation
          add.lines=list(c("N","214,827","182,577","182,577", "94,150", "94,150", "88,427", "88,427"),
                         c("R$^{2}", "0.339", "0.347", "0.347", "0.347", "0.347", "0.347", "0.347"),
                         c("Max. Possible R2", "0.344", "0.350", "0.350",  "0.351", "0.351", "0.349", "0.349"),
                         c("Log Likelihood", "-691.881", "-488.121",  "-487.803", "-317.748", "-317.557", "-163.589", "-163.362")))
##3rd Robustness Check----
#Base model
model_b <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = BrSenSwitch)


seeing <- model_b$data

seeing2 <- model_b$na.action %>% 
           as.data.frame() %>%
           select(x) %>% 
           pull()

seeing_filtered <- seeing %>% 
                   slice(-seeing2) %>%
                   filter(home == 1) %>%
                   mutate(outcome = home - y) %>%
                   mutate(ano = as.factor(ano))

lreg <- glm(outcome ~ alt_swps + dif1 + party_str +
              coligacao_governador + suplente +  legislaturas_participadas + pop_rural,
            family = "binomial", data = seeing_filtered)

lreg_1 <- glm(outcome ~ alt_swps + dif1 + party_str +
                coligacao_governador + suplente +  legislaturas_participadas + pop_rural +
                I(state),   
              family = "binomial", data = seeing_filtered)

lreg_2 <- glm(outcome ~ alt_swps + dif1 + party_str +
                coligacao_governador + suplente +  legislaturas_participadas + pop_rural +
                I(state) + I(ano),   
              family = "binomial", data = seeing_filtered)

lreg_3 <- glm(outcome ~ alt_swps + dif1 + party_str +
                coligacao_governador + suplente +  legislaturas_participadas + pop_rural +
                I(state) + I(ano) + I(partido_inicial),   
              family = "binomial", data = seeing_filtered)

stargazer(lreg, lreg_1, lreg_2, lreg_3,
          dep.var.labels.include = FALSE,
          type="latex",
          #out="table1_panelA.txt", 
          no.space=T, 
          keep = c("alt_swps", "dif1", "party_str", "coligacao_governador", "suplente", "legislaturas_participadas", "pop_rural"),
          keep.stat = c("n","adj.rsq"),  digits = 2, 
          add.lines=list(c("State Fixed Effects","No","Yes","Yes","Yes"),
                         c("Year Fixed Effects","No","No","Yes","Yes"),
                         c("Party Fixed Effects","No","No","No","Yes")),
          covariate.labels = c('Weighted Participation in Coalition', 'Ideological Distance', 'Party Strength',
                               "Governor's Coalition", 'Surrogate', 'Number of Legislatures', 'Rural Population'))

##4th Robustness Check----
lighthouse <- read.csv("BrSenSwitch.csv", sep = ";") %>%
              mutate(fusao = ifelse(is.na(fusao), 0, fusao)) %>%
              mutate(fissao = ifelse(is.na(fissao), 0, fissao)) %>%
              mutate(partido_novo = ifelse(is.na(partido_novo), 0, partido_novo)) %>%
              mutate(home_inverted = 1-home) %>%
              filter(fusao != 1) %>%
              mutate(to_be_elected = case_when(legislatura == 48 ~ 1,
                                               legislatura == 49 ~ 2,
                                               legislatura == 50 ~ 1,
                                               legislatura == 51 ~ 2,
                                               legislatura == 52 ~ 1,
                                               legislatura == 53 ~ 2,
                                               legislatura == 54 ~ 1,
                                               legislatura == 55 ~ 2,
                                               legislatura == 56 ~ 1))

lighthouse2 <- lighthouse %>% filter(to_be_elected == 2) 
lighthouse1 <- lighthouse %>% filter(to_be_elected == 1)



#models without interactions
bc_a <- mclogit(
  y|choice ~ office + dif1 + party_str + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = lighthouse)

bc_b <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = lighthouse)

bc_c <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str*elec_comp + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = lighthouse)

bc_d <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = lighthouse1)

bc_e <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str + party_str*elec_comp +
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = lighthouse1)

bc_f <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = lighthouse2)

bc_g <- mclogit(
  y|choice ~ alt_swps + dif1 + party_str*elec_comp + 
    home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted,
  data = lighthouse2)

#models with clogit
bc1 = clogit(y ~ office + dif1 + party_str + 
                 home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                 strata(choice), data=lighthouse)

bc2 = clogit(y ~ alt_swps + dif1 + party_str + 
                 home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                 strata(choice), data=lighthouse)

bc3 = clogit(y ~ alt_swps + dif1 + party_str*elec_comp + 
                 home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                 strata(choice), data=lighthouse)

bc4 = clogit(y ~ alt_swps + dif1 + party_str + 
                 home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                 strata(choice), data=lighthouse1)


bc5 = clogit(y ~ alt_swps + dif1 + party_str + party_str*elec_comp +
                 home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                 strata(choice), data=lighthouse1)


bc6 = clogit(y ~ alt_swps + dif1 + party_str + 
                 home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                 strata(choice), data=lighthouse2)

bc7 = clogit(y ~ alt_swps + dif1 + party_str*elec_comp + 
                 home + coligacao_governador + suplente*home_inverted + legislaturas_participadas*home_inverted + pop_rural*home_inverted +
                 strata(choice), data=lighthouse2)



stargazer(bc1, bc2, bc3, bc4, bc5, bc6, bc7, type = "text")

stargazer(bc_a, bc_b, bc_c, bc_d, bc_e, bc_f, bc_g, 
          column.labels   = c("Full Dataset", "M = 1", "M = 2"),
          column.separate = c(3, 2, 2),
          no.space=T, order = c(1,2,3,4,7,5,6,8,9, 10), digits = 2, 
          covariate.labels = c("Preisdential Coalition", "Weighted Participation in Coalition", 
                               "Ideological Distance", "Party Strength", "Party Strength * Electoral Competition",
                               "Home Party", "Governor's Coalition", "Surrogate", "Number of Legislatures",
                               "Rural Population"),
          ##input from clogit models for more detailed infmation
          add.lines=list(c("N","244,452","208,480","208,480", "109,767", "109,767", "98,713", "98,713"),
                         c("R$^{2}", "0.335", "0.342", "0.342", "0.341", "0.341", "0.344", "0.344"),
                         c("Max. Possible R2", "0.339", "0.346", "0.346",  "0.345", "0.345", "0.347", "0.347"),
                         c("Log Likelihood", "-739.559", "-587.583",  "-587.352", "-342.931", "-342.710", "-234.882", "-234.743")))